



<template>
  <el-dialog title="新建主体单位"
             v-dialogDrag
             :visible.sync="formVisible"
             :close-on-click-modal="false"
             center
             width="60%"
             :before-close="handleClose"
             >
    <form-assembly-new
      ref="formAssemblyNewRef"
        :entryFrom="entryFrom"
        @makeSure="doCreate"
        @cancel="closeDialog"
    >
    </form-assembly-new>
  </el-dialog>
</template>


<script>
import principalPartApi from '@/api/platformJiaojianyi/principalPart'
import FormAssemblyNew from '@/components/FormAssemblyNew'
import specialAttr from '@/utils/special-attr'

export default {
  name: 'PrincipalPartAdd',
  components: {
    FormAssemblyNew,
  },
  data() {
    return {
    entryFrom: 'add',//入口，add(新增),edit(编辑)，判断是从‘新增’进入，还是从‘编辑’进入，必填
    parentId: '0',
    codeRules: {},
    rowItem: {},
    formObj: {},
      // 动态表单
      dynFormData:{
        formData:{}
      },
 options: {
   parentCode: '',   
},
      formVisible: false,
    }
  },
 async created() {
    this.initApi()
  },
  methods: {
   async initApi () {
      let str = 'insertFormData'//新增编辑展示显示的formdata
      if(this.entryFrom === 'add' || !this.entryFrom){
        str = 'insertFormData'
      }else if(this.entryFrom === 'edit'){
        str = 'updateFormData'
      }else if(this.entryFrom === 'show'){
        str = 'detailFormData'
      }
      let objDatas = [];
      let code = sessionStorage.getItem('routerCode');
      let menus = JSON.parse(sessionStorage.getItem('routerMenus'));
      if(menus!=null){
        menus.forEach((item) => {
          if(item.menuCode==code){
            objDatas.push(item)
          }
        })
      }
      let menusOne = JSON.parse(JSON.stringify(objDatas[0]))
      let formObj = JSON.parse(JSON.stringify(menusOne))
      for (let i = 0; i <  formObj[str].elements.length; i ++) {
          let obj = formObj[str].elements[i];
          // URL
          if (obj.fieldDataType && obj.fieldDataType == 2) {
            let {url, label, value} = obj.dataSources[0];
            let {data} = await principalPartApi.dataApi({url, label, value}) || {}
            this.options[obj.webEntityData] = data;
          } 
          // 静态字符串
          else if (obj.fieldDataType && obj.fieldDataType == 4) {
            let json = obj.dataJson;
            this.options[obj.webEntityData] = JSON.parse(json)
          }
          // 外键
          else if (obj.fieldDataType && (obj.fieldDataType == 3 || obj.fieldDataType == 5)) {
            
            await this['get' + obj.foreignDataClassName + 'Api'](obj.mainFieldLabelName)
          }
      }
    },
    /**
     * 打开新建表单
     */
    handleCreate(menusOne,codeRules) {
      this.codeRules = Object.assign({},codeRules)
      this.formObj = JSON.parse(JSON.stringify(menusOne))
      //获取字典项
      let dictionaryEntry = JSON.parse(sessionStorage.getItem('constCode'))
      if(!dictionaryEntry){
        dictionaryEntry = []
      }

      let str = 'insertFormData'//新增编辑展示显示的formdata
      if(this.entryFrom === 'add' || !this.entryFrom){
        str = 'insertFormData'
      }else if(this.entryFrom === 'edit'){
        str = 'updateFormData'
      }else if(this.entryFrom === 'show'){
        str = 'detailFormData'
      }
    this.formObj[str].elements.forEach((item,index)=>{
        // 组装枚举数据
        if(item.fieldSpecialType === specialAttr.fieldSpecialType.ENUM_TYPE.code){
          item.options = []
          dictionaryEntry.forEach((item1,index1) => {
            if(item1.constCode == item.dicTypeData){
              item.options.push({ label: item1.name, value: item1.value })
            }
          })
        // 组装外键数据
        }else if(item.fieldSpecialType === specialAttr.fieldSpecialType.FK_TYPE.code){
          item.options = this.options[item.foreignData]
        // 组装多对多数据
        }else if(item.fieldSpecialType === specialAttr.fieldSpecialType.MTM_TYPE.code){
          item.options = this.options[item.webEntityData]
        // 组装其他数据
        }else if(item.fieldSpecialType === specialAttr.fieldSpecialType.OTHER_WEB.code){
          item.options = this.options[item.webEntityData]
        }

        // isParentId 代表是tree表
        if(item.isParentId){
          item.value = row.id
          item.options = treeOptions
          this.parentCode = row[item.prop];
          if (!this.parentCode) {
            this.parentCode = ''
          }
        }
        
      })
      this.$set(this.formObj,'subTable',{})
      this.formVisible = true
      this.$nextTick(()=>{
        this.$refs.formAssemblyNewRef.handleAsseData(this.formObj,str)
      })
    },
    /**
     * 执行新建操作
     */
    doCreate(form) {
      form.parentId = this.parentId;
      form.dbCodeIdMap = this.codeRules;
      principalPartApi.insert(form)
        .then(res => {
          if (res.code === '000000') {
            this.$message({
              type: 'success',
              message: '保存成功!'
            })
            this.$emit('created')
            this.$refs.formAssemblyNewRef.handleCancelForm()
            this.formVisible = false
          }else{
            this.$message({
            type: 'error',
            message: res.message
           })
         }
        })
    },
    // 子组件点击取消按钮让dialog的formVisible:false;
    closeDialog(){
      this.formVisible = false;
    },
    // 点击右上角的关闭按钮时让form表单置空
    handleClose(done){
      this.$refs.formAssemblyNewRef.handleCancelForm()
      done();
    }
  }
}
</script>
